{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['no.\" Phone says \"yes.']\n"
     ]
    }
   ],
   "source": [
    "# 问题： 我们正在尝试用正则表达式对文本模式做匹配，但识别出来的是最长的可能匹配。\n",
    "# 相反，我们想要将其修改为最短匹配。\n",
    "# 解决方案： 贪心算法\n",
    "import re\n",
    "\n",
    "str_pat = re.compile(r'\\\"(.*)\\\"')\n",
    "text1 = 'Computer says \"no.\"'\n",
    "# print(str_pat.findall((text1)))\n",
    "\n",
    "# 我们想要 no. 和 yes. 然而只匹配了一个长的。\n",
    "text2 = 'Computer says \"no.\" Phone says \"yes.\"'\n",
    "print(str_pat.findall(text2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['no.', 'yes.']\n"
     ]
    }
   ],
   "source": [
    "# 解决以上问题需要改写正则，在*后面加上问号。表示最短匹配。\n",
    "\n",
    "str_pat = re.compile(r'\\\"(.*?)\\\"')\n",
    "text2 = 'Computer says \"no.\" Phone says \"yes.\"'\n",
    "print(str_pat.findall(text2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 小结： 在*或者+后面添加一个?，会强制将匹配算法寻找最短路径。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2.0
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}